/**
 * @author mikegill74
 * @compid TSTDRV842652
 * @datemod 19/5/2011
 */

/**
 * Globals Variables
 */

var stLogType = 'debug';
var stRecordType = nlapiGetRecordType();
var gType = '';

/**
 * Client-side Functions
 */

/**
 * 
 * Purpose:	
 * 1. Multiple the line amount based on number of outlets specified
 * 2. Set term based on line start date (custom)
 * 
 * @param {Object} type
 * @param {Object} name
 */
function fieldChange_OutletMultiples(type, name){
	
	if (type != 'item') return;
	
	if (nlapiGetCurrentLineItemText(type, 'price') == 'Custom' && (name == 'custcol_at_number_outlets' || name == 'quantity' || name == 'rate')){
		var amount = 0.00;
		amount = (new Number(nlapiGetCurrentLineItemValue(type,'quantity')) * new Number(nlapiGetCurrentLineItemValue(type, 'rate'))) * 
		nlapiGetCurrentLineItemValue(type, 'custcol_at_number_outlets');
		nlapiSetCurrentLineItemValue(type, 'amount', amount);
	}
	
	else if (name == 'custcol_at_start_date' ){
		var dtStartDate= nlapiStringToDate(nlapiGetCurrentLineItemValue('item','custcol_at_start_date'));
		
		if (dtStartDate) {
		
			var intMonths = 12 - parseInt(dtStartDate.getMonth());
			
				switch (intMonths) {
			
				case 1:
					nlapiSetCurrentLineItemValue('item', 'billingschedule', TERMS.ONE)
					break;
				case 2:
					nlapiSetCurrentLineItemValue('item', 'billingschedule', TERMS.TWO)
					break;
				case 3:
					nlapiSetCurrentLineItemValue('item', 'billingschedule', TERMS.THREE)
					break;
				case 4:
					nlapiSetCurrentLineItemValue('item', 'billingschedule', TERMS.FOUR)
					break;
				case 5:
					nlapiSetCurrentLineItemValue('item', 'billingschedule', TERMS.FIVE)
					break;
				case 6:
					nlapiSetCurrentLineItemValue('item', 'billingschedule', TERMS.SIX)
					break;
				case 7:
					nlapiSetCurrentLineItemValue('item', 'billingschedule', TERMS.SEVEN)
					break;
				case 8:
					nlapiSetCurrentLineItemValue('item', 'billingschedule', TERMS.EIGHT)
					break;
				case 9:
					nlapiSetCurrentLineItemValue('item', 'billingschedule', TERMS.NINE)
					break;
				case 10:
					nlapiSetCurrentLineItemValue('item', 'billingschedule', TERMS.TEN)
					break;	
				case 11:
					nlapiSetCurrentLineItemValue('item', 'billingschedule',TERMS.ELEVEN)
					break;
				case 12:
					nlapiSetCurrentLineItemValue('item', 'billingschedule', TERMS.TWELVE)
					break;	
			}	
			
		}
	}
	

	
}

/**
 * Purpose: Ensure that Billing startdate and first recurring item startdate (custom field) are in sync
 */

function pageInit(type){
	
	gType = type;
}

function saveRecord_ContractValidation(){
	
	//alert(nlapiGetFieldValue('status'));

	if (gType == 'edit' || gType == 'create') {
	
		var stHeaderStartDate = nlapiGetFieldValue('startdate');
		var stStatus = nlapiGetFieldValue('status');
	
		var stLineStartDate = '';
		var LineDatesObj = {};
		var LineDatesArr = [];
	
		
		for (var i = 1; i <= nlapiGetLineItemCount('item'); i++) {
		
			LineDatesObj = new Object();
			LineDatesObj.startdate = '', percent = '', item = '';
			LineDatesObj.startdate = nlapiGetLineItemValue('item', 'custcol_at_start_date', i);
			LineDatesObj.percent = nlapiGetLineItemValue('item', 'percentcomplete', i);
			LineDatesObj.schedule = nlapiGetLineItemValue('item','billingschedule', i);
			
			if (stLineStartDate == '') {
				var stLineStartDate = nlapiGetLineItemValue('item', 'custcol_at_start_date', i);
			}
			
			LineDatesArr.push(LineDatesObj);
			
			
		}
		
		//alert('Status = '+ stStatus + ':' +LineDatesArr.length);
		
		if (stStatus == 'Partially Fulfilled' || stStatus == 'Pending Billing/Partially Fulfilled') {
			
			var intBillingStarted = 0;
			
			
			
			for (var i = 0; i < LineDatesArr.length; i++) {
			
				//alert('Schedule = ' +LineDatesArr[i].schedule );
				
				if (new Number(LineDatesArr[i].schedule) > 0) {
					
					//alert('Percent complete =  ' + LineDatesArr[i].percent);
					
					if (LineDatesArr[i].percent == '0.0%' || LineDatesArr[i].percent == '') {
					
						intBillingStarted =+ 1;
					}
				}
				
			}
			
			
			
			if (intBillingStarted > 0) {
				 
				var r= confirm('New subscriptions items added - Copy/create new contract?');
					if (r){
						var today = new Date();
						nlapiSetFieldValue('enddate',nlapiDateToString(today));
						
						
						
						return true;
					}
					
					else{
						return false;
					}
				
				return true;
			}
			
		}
		

		
			if (stHeaderStartDate != stLineStartDate) {
			
				alert('Contract Warning: Billing startdate must have the same startdate as the first recurring line item.');
				return false;
				
			}
			
		
		else 
			return true;
			
	}// close type
	
	return true;
}



/**
 * Purpose: Force quantity to be same as Billing schedule term
 * @param {Object} type
 * @param {Object} name
 */

function validateLine_ContractValidation(type){
	
	if (type == 'item') {
		
		var intBillingSchedule = nlapiGetCurrentLineItemText(type, 'billingschedule');
		var intQuantity = nlapiGetCurrentLineItemValue(type, 'quantity');
		
		if (intBillingSchedule != intQuantity && (intBillingSchedule > 1)) {
			nlapiSetCurrentLineItemValue(type,'quantity',intBillingSchedule);
		}
		
		return true;
		
	}
	
	
	return true;
	
}

function postSourcing_SetPriceLevelToClass(type, name){
	
	if (type == 'item' && name == 'item') {
	
		nlapiSetCurrentLineItemText('item', 'price', nlapiGetFieldText('class'));
	}
	
}



/**
 * @Server-side Functions
 */

/**
 * 
 * Purpose:	Main before submit function
 * 
 * @param {Object} type
 */

function beforeSubmit_Main(type){
	
	if (type != 'create' && type != 'edit')return;
	
	
	if (stRecordType == 'salesorder') {
	
		ContractAutomation();
	
		try {
		
			
			
		} 
		
		catch (e) {
			if (e.getDetails != undefined) {
				nlapiLogExecution(stLogType, 'Contract  Error: <br>' + e.getCode() + '<br>' + e.getDetails() + '<br>' + e.getStackTrace());
			}
			else {
				nlapiLogExecution(stLogType, 'Contract  Error: <br>' + e.description);
			}
		}
	}
	
	else if (stRecordType == 'invoice'){
		
		try {
			PeriodsInvoice();
		}
		
		catch (e){
			if (e.getDetails != undefined) {
				nlapiLogExecution(stLogType, 'Contract Error: <br>' + e.getCode() + '<br>' + e.getDetails() + '<br>' + e.getStackTrace());
			}
			else {
				nlapiLogExecution(stLogType, 'Contract Error: <br>' + e.description);
			}
		}
		
	}
	
	
}


/**
 * Purpose: If first Invoice is created after the 15th, then amount is 50% only
 */

function PartialInvoice(){
	
}

/**
 * Purpose: Set Start Date (startdate) & End Date (enddate) on the Invoice for Period
 */

function PeriodsInvoice(){
	
		// Period Computation
    	var currentDate = new Date(nlapiStringToDate(nlapiGetFieldValue('trandate')));
    	var stCurrentDate = nlapiDateToString(currentDate);
    	currentDate.setDate(1); // set the 1st day of the month
    	var stFirstDayOfMonth = nlapiDateToString(currentDate);
		var intDays = daysInMonth(currentDate.getMonth(), currentDate.getYear());
		var stLastDayOfMonth = nlapiDateToString(nlapiAddDays(currentDate,intDays-1));
		nlapiSetFieldValue('startdate',stFirstDayOfMonth);
		nlapiSetFieldValue('enddate',stLastDayOfMonth);
	
	
}


/**
 * Purpose: Renewals
 */


function RenewalsSuiteLet(request, response){
	
	
	if (request.getMethod() == 'GET'){
		 
		 	var form = nlapiCreateForm("Suitelet - Renewals");''
		 	form.addSubmitButton('Submit');
    		response.writePage(form);
	}
	
	else {
			var form = nlapiCreateForm("SuiteLet - Renewals");
    		response.writePage(form);
	}
	
}


function Renewals(){
	
}


/**
 * Purpose: Set Line Billing Schedule based on (Year End - Line Start Date)
 */

function ContractAutomation(){


	var dtEndDate = nlapiStringToDate(nlapiGetFieldValue('enddate'));
	
	if (dtEndDate) {
	
		for (var i = 1; i <= nlapiGetLineItemCount('item'); i++) {
		
			dtEndDate.setHours(0);
			dtEndDate.setMilliseconds(0);
			dtEndDate.setMinutes(0);
			dtEndDate.setSeconds(0);
			
			var dtToday = new Date();
			dtToday.setHours(0);
			dtToday.setMilliseconds(0);
			dtToday.setMinutes(0);
			dtToday.setSeconds(0);
			
			
			//throw dtToday + ":" +dtEndDate;
			
			if (dtEndDate.valueOf() == dtToday.valueOf()) {
			
				nlapiSetLineItemValue('item', 'isclosed', i, 'T');
			}
			
			
			
		}
		
	}
	
	
}

function TERMS(){};
	
	TERMS.ONE = 4;
	TERMS.TWO = 5;
	TERMS.THREE = 7;
	TERMS.FOUR = 6;
	TERMS.FIVE = 8;
	TERMS.SIX = 9;
	TERMS.SEVEN = 10;
	TERMS.EIGHT = 11;
	TERMS.NINE = 3;
	TERMS.TEN = 12;
	TERMS.ELEVEN = 13;
	TERMS.TWELVE = 1;


